package cn.eeepay.framework.service.impl;

import cn.eeepay.framework.dao.WarningConfigTemplateDao;
import cn.eeepay.framework.model.JumpRouteConfig;
import cn.eeepay.framework.model.JumpWarn;
import cn.eeepay.framework.model.WarningConfigTemplate;
import cn.eeepay.framework.service.JumpRouteService;
import cn.eeepay.framework.service.JumpWarnService;
import cn.eeepay.framework.service.WarningConfigTemplateService;
import cn.eeepay.framework.util.Sms;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class WarningConfigTemplateServiceImpl implements WarningConfigTemplateService {

    private Logger logger = LoggerFactory.getLogger(WarningConfigTemplateServiceImpl.class);

    @Autowired
    private WarningConfigTemplateDao warningConfigTemplateDao;
    @Autowired
    private JumpWarnService jumpWarnService;
    @Autowired
    private JumpRouteService jumpRouteService;

    @Override
    public void earlyWarningCheck() {
        List<WarningConfigTemplate> list = warningConfigTemplateDao.select();
        WarningConfigTemplate warningConfigTemplate = null;
        if(CollectionUtil.isNotEmpty(list)){
            for (WarningConfigTemplate template : list) {
                if(template.getWarnType() == 5){
                    warningConfigTemplate = template;
                    break;
                }
            }
        }
        if(warningConfigTemplate == null){
            logger.info("未达标预警未设置，定时任务无需运行...");
            return ;
        }
        String toDayStr = DateUtil.today();
        Date toDay = new Date();                //2个toDay做公共变量，防止中途跨天

        List<JumpWarn> jumpWarns = jumpWarnService.select();
        for (JumpWarn jumpWarn : jumpWarns) {
            if(jumpWarn.getLastWarnTime() != null){
                String lastWarnDate = DateUtil.format(jumpWarn.getLastWarnTime(), "yyyy-MM-dd");
//                    String yesterDay = DateUtil.format(DateUtil.yesterday(), "yyyy-MM-dd");     //昨天
                if(!lastWarnDate.equals(toDayStr)){     //如果最后一次预警不是今天，那么更新预警数据为今天并且设置今天为未预警
                    jumpWarn.setWarnStatus(0);
                    jumpWarn.setLastWarnTime(new Date());
                    jumpWarnService.updateLastWarnTime(jumpWarn.getId(),0,toDay);
                }
            }
            String warnTimeFormat = DateUtil.format(jumpWarn.getWarnTime(), "HH:mm:ss");
            String warnTimeStr = toDayStr+" "+warnTimeFormat;
            long warnTime = DateUtil.parse(warnTimeStr).getTime();
            long currentTime = toDay.getTime();
            if(currentTime >= warnTime && jumpWarn.getWarnStatus() == 0){        //如果已经到了预警时间,并且未预警
                JumpRouteConfig config = jumpRouteService.findById(jumpWarn.getJumpId());
                if(config != null){
                    BigDecimal scale = jumpWarn.getScale();            //预警比例
                    BigDecimal targetAmount = config.getTargetAmount();     //目标金额
                    BigDecimal totalAmount = config.getTotalAmount();       //已跑量金额
                    BigDecimal scale2 = totalAmount.divide(targetAmount,2,RoundingMode.HALF_UP).multiply(new BigDecimal("100"));        //已跑量百分比

                    if(scale2.compareTo(scale) < 0){
                        String msgTemplate = warningConfigTemplate.getMsgTemplate();
                        msgTemplate = msgTemplate.replace("time",jumpWarn.getWarnTimeStr());
                        msgTemplate = msgTemplate.replace("routeId",jumpWarn.getJumpId().toString());
                        msgTemplate = msgTemplate.replace("remake",config.getRemark());
                        msgTemplate = msgTemplate.replace("amount",totalAmount.toString());
                        msgTemplate = msgTemplate.replace("scale1",scale2.toString()+"%");
                        String msg = msgTemplate.replace("scale2",scale.toString()+"%");

                        String[] split = warningConfigTemplate.getMsgReceiver().split(",");
                        for (String phone : split) {
                            Sms.sendMsg(phone,msg);
                        }
                        jumpWarnService.updateLastWarnTime(jumpWarn.getId(),1,toDay);       //设置为已预警
                    }
                }else{
                    logger.info("跳转集群金额短信预警集群id未找到:{}",jumpWarn.getJumpId());
                }
            }
        }

    }

}
